package utils

import (
	"fmt"

	"gitee.com/go-micro-services/consul-http/conf"
	"github.com/hashicorp/consul/api"
)

var ConsulClient *api.Client

// 获取consul客户端
func GetConsulClient() (*api.Client, error) {
	// 获取缓存
	if ConsulClient != nil {
		return ConsulClient, nil
	}
	// 获取注册中心连接客户端
	defaultConfig := api.DefaultConfig()
	defaultConfig.Address = conf.ConsulAddr
	ConsulClient, err := api.NewClient(defaultConfig)
	return ConsulClient, err
}

// 当前http服务注册到consul
func ConsulHttpReg() error {
	// 获取注册中心连接客户端
	client, err := GetConsulClient()
	if err != nil {
		return err
	}
	// 注册实例配置
	agentServiceRegistration := new(api.AgentServiceRegistration)
	agentServiceRegistration.Address = conf.HttpHost
	agentServiceRegistration.Port = conf.HttpPort
	agentServiceRegistration.Name = conf.HttpName
	agentServiceRegistration.ID = conf.HttpId
	agentServiceRegistration.Tags = conf.HttpTags
	httpAddr := fmt.Sprintf("http://%s/health", conf.HttpAddr)
	check := api.AgentServiceCheck{
		HTTP:                           httpAddr,
		Timeout:                        "3s",
		Interval:                       "1s",
		DeregisterCriticalServiceAfter: "3s",
	}
	agentServiceRegistration.Check = &check
	// 注册
	return client.Agent().ServiceRegister(agentServiceRegistration)
}

// 工具函数
func GetServiceList() (map[string]*api.AgentService, error) {
	// 获取注册中心连接客户端
	client, err := GetConsulClient()
	if err != nil {
		return nil, err
	}
	services, err := client.Agent().Services()
	return services, err
}

// 过滤服务
func FilterService(service string) (map[string]*api.AgentService, error) {
	// 获取注册中心连接客户端
	client, err := GetConsulClient()
	if err != nil {
		return nil, err
	}
	// 过滤条件
	filterCondition := fmt.Sprintf("Service==%v", service)
	services, err := client.Agent().ServicesWithFilter(filterCondition)
	return services, err
}
